import 'package:flutter/material.dart';
import 'package:qrscan/qrscan.dart' as scanner;
import 'dart:async';

/// 系统首页
class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => new _HomePageState();
}

class _HomePageState extends State<HomePage> {

  String barcode = "Nothing";

  // 扫描二维码
  Future _scanCode() async {
    try {
      barcode = await scanner.scan();
      setState(() => this.barcode = barcode);
    } on Exception catch (e) {
      // ignore: unrelated_type_equality_checks
      if (scanner.CameraAccessDenied == e) {
        setState(() {
          this.barcode = 'The user did not grant the camera permission!';
        });
      } else {
        setState(() => this.barcode = 'Unknown error: $e');
      }
    // ignore: dead_code_on_catch_subtype
    } on FormatException {
      setState(() => this.barcode = 'null (User returned using the "back"-button before scanning anything. Result)');
    } catch (e) {
      setState(() => this.barcode = 'Unknown error: $e');
    } 
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter 扫描二维码和条形码"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                child: Wrap(
                  children: [
                    Text(
                      "扫描结果: $barcode",
                      style: TextStyle(
                        fontSize: 24.0,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ]
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.scanner),
        onPressed: _scanCode,
      ),
    );
  }
}